package com.sicnu.cheer.profileset.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sicnu.cheer.generalmodule.bean.JoinLeagueBean;
import com.sicnu.cheer.generalmodule.bean.LeagueBean;
import com.sicnu.cheer.generalmodule.bean.MyUser;
import com.sicnu.cheer.generalmodule.config.AppManager;
import com.sicnu.cheer.generalmodule.util.DateUtil;
import com.sicnu.cheer.generalmodule.util.ImageUtils;
import com.sicnu.cheer.generalmodule.util.SharedPreferencesUtil;
import com.sicnu.cheer.generalmodule.util.StringUtils;
import com.sicnu.cheer.generalmodule.util.UIHelper;
import com.sicnu.cheer.profileset.R;
import com.sicnu.cheer.profileset.config.Constant;
import com.sicnu.cheer.profileset.dialog.DialogsUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import io.github.lijunguan.imgselector.ImageSelector;

import static com.sicnu.cheer.profileset.config.Constant.BACK_FROM_GROUP;
import static com.sicnu.cheer.profileset.config.Constant.BIRTHDAY;
import static com.sicnu.cheer.profileset.config.Constant.HEADPIC;
import static com.sicnu.cheer.profileset.config.Constant.HOMETOWN;
import static com.sicnu.cheer.profileset.config.Constant.NICKNAME;
import static com.sicnu.cheer.profileset.config.Constant.SEX;

/**
 * Created by cheer on 2017/1/23.
 * 个人资料展示页，可进行修改
 */
public class MyProfileActivity extends Activity implements View.OnClickListener{

    private MyProfileActivity mThis;
    private ImageView photoIV;
    private TextView sexTV;
    private TextView ageTV;
    private TextView nickNameTV;
    private TextView hometownTV;
    private TextView groupTV;

    private RelativeLayout changePhoto;
    private ProgressDialog progressDialog;
    private boolean isChanged;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_profile);
        mThis = this;
        initData();
        initView();
        fillView();
        AppManager.getAppManager().addActivity(mThis);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        progressDialog = new ProgressDialog(mThis);
        progressDialog.setMessage("加载中...");
    }

    /**
     * 初始化界面上的控件
     */
    private void initView() {
        ((TextView) findViewById(R.id.title)).setText("个人资料");
        findViewById(R.id.back).setOnClickListener(this);

        photoIV = ((ImageView) findViewById(R.id.photo_iv));
        photoIV.setOnClickListener(this);

        changePhoto = ((RelativeLayout) findViewById(R.id.my_photo_rl));
        changePhoto.setOnClickListener(this);

        sexTV = ((TextView) findViewById(R.id.sex_tv));
        findViewById(R.id.my_sex).setOnClickListener(this);

        ageTV = ((TextView) findViewById(R.id.age_tv));
        findViewById(R.id.my_age).setOnClickListener(this);

        hometownTV = ((TextView) findViewById(R.id.height_tv));
        findViewById(R.id.my_hometown).setOnClickListener(this);

        nickNameTV = ((TextView) findViewById(R.id.nickname_tv));
        findViewById(R.id.my_nickname).setOnClickListener(this);

        findViewById(R.id.my_password).setOnClickListener(this);

        groupTV = ((TextView) findViewById(R.id.group_tv));
        findViewById(R.id.my_group).setOnClickListener(this);
    }

    /**
     * 填充界面
     */
    private void fillView() {

        MyUser myUser = MyUser.getCurrentUser(mThis, MyUser.class);
        if (myUser != null) {
            Glide.with(mThis).load(myUser.getHeadPic()).placeholder(R.mipmap.default_user_img).into(photoIV);
            sexTV.setText(myUser.getSex());
            int ageInt=0;
            if (!StringUtils.isEmpty(myUser.getBirthday())) {
                ageInt= DateUtil.getAge(DateUtil.convertDate(myUser.getBirthday(), Constant.yyyy_MM_dd_PATTERN));
            }
            ageTV.setText(ageInt + "");
            hometownTV.setText(myUser.getHometown());
            nickNameTV.setText(myUser.getNick());

            final LeagueBean league = myUser.getLeague();
            if (league!=null){
                BmobQuery<LeagueBean> query=new BmobQuery();
                query.addWhereEqualTo("objectId",league.getObjectId());
                query.findObjects(mThis, new FindListener<LeagueBean>() {
                    @Override
                    public void onSuccess(List<LeagueBean> list) {
                        if (list!=null&&list.size()>0) {
                            groupTV.setText(list.get(0).getName());
                        }
                    }
                    @Override
                    public void onError(int i, String s) {
                    }
                });
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.back) {
            onBackPressed();
        } else if (v.getId() == R.id.photo_iv) {
            //弹出框显示
            String imgUrl = MyUser.getCurrentUser(mThis,MyUser.class).getHeadPic();
            ImageUtils.showBigImageDialog(mThis, R.layout.image_dialog, imgUrl, null);
        } else if (v.getId() == R.id.my_photo_rl) {
            //1.
            changeAvatar();
        } else if (v.getId() == R.id.my_sex) {
            //2.
            showSexChooseDialog();
        } else if (v.getId() == R.id.my_age) {

            //3.
            showDatePickerDialog();
        } else if (v.getId() == R.id.my_hometown) {
            //4.
            showHometownChooseDialog();
        } else if (v.getId() == R.id.my_nickname) {
            //5.
            showNicknameChangeDialog();
        } else if (v.getId() == R.id.my_group) {
            //6.
            changeGroup();
        }else if (v.getId()==R.id.my_password){
            showPasswordChangeDialog();
        }
    }

    /**
     * 1
     * 修改头像
     */
    private void changeAvatar() {
        ImageSelector.getInstance()
                .setSelectModel(ImageSelector.AVATOR_MODE)
                .setGridColumns(3)
                .setShowCamera(true)
                .setToolbarColor(getResources().getColor(R.color.theme_green_color))
                .startSelect(this);
    }


    /**
     * 从选择图片或者拍照返回，或者选择社团activity返回
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ImageSelector.REQUEST_SELECT_IMAGE
                && resultCode == RESULT_OK) {
            ArrayList<String> imagesPath = data.getStringArrayListExtra(ImageSelector.SELECTED_RESULT);
            if(imagesPath != null){
                progressDialog.show();
                final BmobFile bmobFile = new BmobFile(new File(imagesPath.get(0)));
                bmobFile.uploadblock(mThis, new UploadFileListener() {
                    @Override
                    public void onSuccess() {
                        deleteOldAvatar();
                        final String picPath =bmobFile.getFileUrl(mThis);
                        updateUserInfo(HEADPIC,picPath, new OnUpdateUserInfoSuccessListener() {
                            @Override
                            public void updateSuccess() {
                                SharedPreferencesUtil.saveUserItem(mThis,HEADPIC,picPath);
                                Glide.with(mThis).load(picPath).placeholder(R.mipmap.default_user_img).into(photoIV);
                            }
                        });
                    }

                    @Override
                    public void onProgress(Integer value) {
                        // 返回的上传进度（百分比）
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        UIHelper.ToastMessage(mThis,"上传文件失败：" + msg);
                    }
                });
            }
        }else if (requestCode==BACK_FROM_GROUP&&resultCode==2){
            //选择社团后有返回的操作
            final LeagueBean bean = (LeagueBean) data.getSerializableExtra("bean");
            if (bean !=null){
                progressDialog.show();
                MyUser myUser=MyUser.getCurrentUser(mThis,MyUser.class);
                myUser.setLeague(bean);
                myUser.update(mThis, myUser.getObjectId(), new UpdateListener() {
                    @Override
                    public void onSuccess() {
                        progressDialog.dismiss();
                        UIHelper.ToastMessage(mThis,"切换社团成功");
                        groupTV.setText(bean.getName());
                        isChanged=true;
                    }
                    @Override
                    public void onFailure(int i, String s) {
                        progressDialog.dismiss();
                        UIHelper.ToastMessage(mThis,"切换社团失败："+s);
                    }
                });
            }
        }
    }

    /**
     * 删除用户之前的头像
     */
    private void deleteOldAvatar() {
        MyUser myUser=MyUser.getCurrentUser(mThis,MyUser.class);
        BmobFile file = new BmobFile();
        file.setUrl(myUser.getHeadPic());//此url是上传文件成功之后通过bmobFile.getUrl()方法获取的。
        file.delete(mThis, new DeleteListener() {

            @Override
            public void onSuccess() {
                Log.d("success","文件删除成功");
            }

            @Override
            public void onFailure(int code, String msg) {
                Log.e("error", "onFailure: 文件删除失败"+msg);
            }
        });
    }

    /**
     * 2.
     * 弹出性别选择对话框进行选择，上传服务器
     */
    private void showSexChooseDialog() {
        int s = 1;
        if (sexTV.getText().toString().equals("女")) {
            s = 2;
        }
        DialogsUtil.showSexChooseDialog(mThis, s, new DialogsUtil.DialogCallback() {
            @Override
            public void confirmCallBack() {
                final String str = SharedPreferencesUtil.getUserItem(mThis,SEX);
                updateUserInfo(SEX, str, new OnUpdateUserInfoSuccessListener() {
                    @Override
                    public void updateSuccess() {
                        sexTV.setText(str);
                    }
                });
            }

            @Override
            public void cancelCallBack() {
            }
        });
    }

    /**
     * 3.
     * 弹出时间选择对话框选择生日
     */
    private void showDatePickerDialog() {
        MyUser myUser = MyUser.getCurrentUser(mThis, MyUser.class);
        if (myUser != null) {
            DialogsUtil.showBirthdayChooseDialog(mThis, myUser.getBirthday(), new DialogsUtil.DialogCallback() {
                @Override
                public void confirmCallBack() {
                    final String birthday = SharedPreferencesUtil.getUserItem(mThis,BIRTHDAY);
                    updateUserInfo(BIRTHDAY, birthday, new OnUpdateUserInfoSuccessListener() {
                        @Override
                        public void updateSuccess() {
                            int ageInt = DateUtil.getAge(DateUtil.convertDate(birthday, Constant.yyyy_MM_dd_PATTERN));
                            ageTV.setText(ageInt + "");
                        }
                    });
                }

                @Override
                public void cancelCallBack() {

                }
            });
        }
    }

    /**
     * 4
     * 选择家乡
     */
    private void showHometownChooseDialog() {
        DialogsUtil util=new DialogsUtil();
        util.showHometownChooseDialog(mThis, new DialogsUtil.DialogCallback() {
            @Override
            public void confirmCallBack() {
                final String hometown=SharedPreferencesUtil.getUserItem(mThis,HOMETOWN);
                updateUserInfo(HOMETOWN, hometown, new OnUpdateUserInfoSuccessListener() {
                    @Override
                    public void updateSuccess() {
                        hometownTV.setText(hometown);
                    }
                });
            }

            @Override
            public void cancelCallBack() {

            }
        });
    }

    /**
     * 5
     * 对话框修改昵称
     */
    private void showNicknameChangeDialog() {
        MyUser myUser = MyUser.getCurrentUser(mThis, MyUser.class);
        if (myUser != null) {
            UIHelper.inputDialog(mThis, "修改昵称", myUser.getNick(), "昵称(不超过5个字)", new UIHelper.InputDialogCallback() {
                @Override
                public void confirmCallBack(String text, String value) {
                    final String va=value;
                    updateUserInfo(NICKNAME, value, new OnUpdateUserInfoSuccessListener() {
                        @Override
                        public void updateSuccess() {
                            nickNameTV.setText(va);
                        }
                    });
                }

                @Override
                public void cancelCallBack(String text) {

                }
            });

        }
    }
    /**
     * 6.切换用户当前的社团
     */
    private void changeGroup() {
        BmobQuery<JoinLeagueBean> query=new BmobQuery<>();
        query.addWhereEqualTo("myUser",BmobUser.getCurrentUser(mThis));
        query.addWhereEqualTo("pass",1);
        query.addQueryKeys("leagueBean");
        query.include("leagueBean");
        query.findObjects(mThis, new FindListener<JoinLeagueBean>() {
            @Override
            public void onSuccess(List<JoinLeagueBean> list) {
                ArrayList<LeagueBean> leagueList=new ArrayList<LeagueBean>();
                LeagueBean commonLg=new LeagueBean();
                commonLg.setObjectId(mThis.getResources().getString(R.string.objId));
                commonLg.setName(mThis.getResources().getString(R.string.name));
                commonLg.setLogo(mThis.getResources().getString(R.string.logo));
                leagueList.add(commonLg);

                for (JoinLeagueBean bean:list){
                    leagueList.add(bean.getLeagueBean());
                }
                if (leagueList.size()>0){
                    Intent intent = new Intent();
                    intent.setClassName(mThis,"com.sicnu.cheer.leaugebar.managemodule.activity.LeagueDisplayActivity");
                    intent.putExtra("title","选择社团");
                    intent.putExtra("list",leagueList);
                    startActivityForResult(intent,Constant.BACK_FROM_GROUP);
                }
            }

            @Override
            public void onError(int i, String s) {

            }
        });

    }

    /**
     * 弹出修改密码对话框
     */
    private void showPasswordChangeDialog(){
        DialogsUtil.showChangePasswordDialog(mThis, new DialogsUtil.InputDialogCallback() {
            @Override
            public void confirmCallBack(String oldValue, String newValue) {
                BmobUser.updateCurrentUserPassword(mThis, oldValue, newValue, new UpdateListener() {
                    @Override
                    public void onSuccess() {
                        UIHelper.ToastMessage(mThis, "重置密码成功，请用新密码进行登录");
                        BmobUser.logOut(mThis);
                        Intent intent=new Intent();
                        intent.setClassName(mThis,"com.sicnu.cheer.leaugebar.activity.LoginActivity");
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onFailure(int code, String msg) {
                        UIHelper.ToastMessage(mThis,"重置失败："+msg);
                    }
                });
            }

            @Override
            public void cancelCallBack() {

            }
        });
    }
    /**
     * 修改用户信息
     * @param key 需要修改的信息的键值
     * @param value 修改的value
     * @param listener 修改成功的监听
     */
    private void updateUserInfo(String key, String value, final OnUpdateUserInfoSuccessListener listener) {
        if (progressDialog != null&&!progressDialog.isShowing()) {
            progressDialog.show();
        }
        MyUser myUser = new MyUser();
        switch (key) {
            case SEX:
                myUser.setSex(value);
                break;
            case BIRTHDAY:
                myUser.setBirthday(value);
                break;
            case HOMETOWN:
                myUser.setHometown(value);
                break;
            case NICKNAME:
                myUser.setNick(value);
                break;
            case HEADPIC:
                myUser.setHeadPic(value);
                break;

        }
        myUser.setInit(true);
        myUser.update(mThis, BmobUser.getCurrentUser(mThis).getObjectId(), new UpdateListener() {
            @Override
            public void onSuccess() {
                listener.updateSuccess();
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
            }

            @Override
            public void onFailure(int i, String s) {
                UIHelper.ToastMessage(mThis, "个人资料设置失败：" + s);
                if (progressDialog != null) {
                    progressDialog.dismiss();
                }
            }
        });
    }

    /**
     * 更新用户信息成功的接口
     */
    public interface OnUpdateUserInfoSuccessListener {
        void updateSuccess();
    }

    @Override
    public void onBackPressed() {
        Intent intent=new Intent();
        intent.putExtra("changeLeague",isChanged);
        setResult(Constant.RESULT_FROM_PROFILE_SET,intent);
        super.onBackPressed();
    }
}
